package auth;

import function.UseDatabase;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AuthManager {

    //存储当前有的所有可操作权限
    private static final List<String> ALL_PERMISSION = new ArrayList<>(Arrays.asList("SELECT", "INSERT", "UPDATE", "DELETE"));

    public static boolean authenticate() throws IOException, DocumentException {
        //获得用户输入ID和PASSWORD
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("请输入用户名：");
        String name = bufferedReader.readLine();
        System.out.println("请输入密码：");
        String password = bufferedReader.readLine();

        //验证请求登陆的用户信息
        Document document = new SAXReader().read("./mydatabase/user/user.xml");
        org.dom4j.Element node = (org.dom4j.Element) document.selectSingleNode("users/user[@name='" + name + "'and @password='" + password + "']");
        if (node != null) {
            //获取用户的Id 查询其权限
            String id = node.attributeValue("id");
            saveUserPermission(id);
            System.out.println("用户权限已保存" + "       " + UseDatabase.ROLE.toString());
            return true;
        }
        System.out.println("保存用户权限失败");
        return false;
    }


    //保存用户的权限到Java内存
    private static void saveUserPermission(String id) {
        try {
            Document rolesDoc = new SAXReader().read("./mydatabase/user/roles.xml");
            // 使用XPath查询找到对应角色
            Element roleElement = (Element) rolesDoc.selectSingleNode("//role[id='" + id + "']");
            if (roleElement != null) {
                // 获取permissions子元素
                Element permissionsElement = roleElement.element("permissions");
                if (permissionsElement != null) {
                    // 获取所有permission元素
                    List<Element> permElements = permissionsElement.elements("permission");
                    for (Element permElement : permElements) {
                        // 添加权限到全局变量
                        UseDatabase.ROLE.add(permElement.getTextTrim());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //权限校验,传过来是什么操作,再对比内存中是否存储该用户有没有该权限
    public static boolean hasPermission(String permission) {
        //判断是否是当前可管理的操作, 是则判断有无权限, 否则直接可操作
        boolean isPer = ALL_PERMISSION.stream().anyMatch(permission.toUpperCase()::equals);
        if (isPer)
            return UseDatabase.ROLE.stream().anyMatch(permission.toUpperCase()::equals);
        return true;
    }

}
